import React,{ useState,useEffect,useCallback, useRef } from "react";
import { useDispatch,useSelector } from 'react-redux'
import { useHistory } from 'react-router-dom'

import { userLoginSaga } from './store/actionCreator'

import Loginimg from "@/assets/image/login.jpg";
import { LoginWrapper } from "./styledLogin";
import NavBar from "@/components/navBar/NavBar";
import Button from "@/components/button/Button";

export default function Login() {
  const user = useSelector(state => {
    return state.getIn(['Login','userLogin'])
  })
  const [ checked,setChecked ] = useState(false)
  const [ num,setNum]=useState() //手机号码
  const  [pass,setPass]=useState() //密码
  
  const dispatch = useDispatch()
  
  const telInput = useRef()  
  const passInput = useRef() 
  
  const history = useHistory() 

  const changeChecked = useCallback(
    () => {
      setChecked(!checked)
    },
    [checked,setChecked],
  )

   const changeNum=useCallback(
     () => {
      setNum(telInput.current.value)
     },
     [setNum,telInput],
   )

   const changePass = useCallback(
    () => {
      setPass(passInput.current.value)
     
     },
     [setPass,passInput],
   )
   const submit = useCallback(
    () => {
      if(checked){
          dispatch(userLoginSaga({
          'num': num,
          'pass': pass
        }))
      }
     },
     [dispatch,num,pass,checked],
   )
  
   useEffect(() => {
     console.log(user);
     if(Object.keys(user).length!==0){
      history.push('/home')
     }
   }, [user,history])

   const toRegister=useCallback(
    ()=>{
      history.push('/register')
    }
  )
  return (
    <LoginWrapper>
      <NavBar leftArrow> </NavBar>
      <div className="content">
        <img src={Loginimg} />
        <div className="all">
          <div className="title">手机验证码登录</div>
          <div className="welcome">欢迎使用家医</div>
        </div>
        <div className="form">
          <div className="tl">手机号码</div>
          <input className="phone" type="text" value={num || ''}  onChange={changeNum} ref={telInput} placeholder="请输入手机号码" />
          <div className="tl">密码</div>
          <input className="pass" type="password" value={pass || ''} onChange={changePass} ref={passInput} placeholder="请输入密码" />
          <div className="read">
            <input type="checkbox" value={checked} onChange={changeChecked} />
            <span className='ok'>
              我已阅读并同意 <b>《用户隐私政策》</b>
            </span>
            <span className="memo">忘记密码？</span>
          </div>
          <Button text="登录" size="large" click={submit}></Button>
          
        </div>
        <div className='bottom'>
            <span>免密登录</span>
            <span onClick={toRegister}>注册新用户</span>
        </div>
      </div>
    </LoginWrapper>
  );
}
